package com.kaigejava.redis.cofig;

import com.kaigejava.redis.cofig.fst.FstSerializationRedisSerializer;
import org.nustaq.serialization.FSTConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;


/**
 * @author 凯哥Java
 * @description
 * @company
 * @since 2023/3/28 22:27
 */

@Configuration
@ConditionalOnProperty(prefix = "spring.redis",name = "serializer",havingValue = "fst")
public class JetLinksRedisConfiguration {
    @Bean
    public RedisTemplate<String, Object> redisTemplate( RedisConnectionFactory connectionFactory, ResourceLoader resourceLoader){
        // 创建RedisTemplate对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(connectionFactory);
        // 创建JSON序列化工具
      /*  GenericJackson2JsonRedisSerializer jsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();*/
        FstSerializationRedisSerializer jsonRedisSerializer = new FstSerializationRedisSerializer(() -> {
            FSTConfiguration configuration = FSTConfiguration.createDefaultConfiguration()
                    .setForceSerializable(true);
            configuration.setClassLoader(resourceLoader.getClassLoader());
            return configuration;
        });

        // 设置Key的序列化
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置Value的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);
        // 返回
        return template;
    }
}
